using ASP;
using ClassLibrary.BusinessLayer.Facade;
using IPMS.AccessAuth;
using IPMS.BLL;
using Resources;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Globalization;
using System.Threading;
using System.Web.Profile;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class HeadingTmplt : Page, IRequiresSessionState
{
    
    /// <summary>
    /// ClearGroupType checkbox (add by ljr)
    /// </summary>
    private void ClearGroupType()
    {
        foreach (RepeaterItem rptItem in rptGroupType.Items)
        {
            CheckBox cb = (CheckBox)rptItem.FindControl("chkGroupTP");
            cb.Checked = false;
        }
    }

    private void InitddlSection()
    {
        /*
        ListItem item = new ListItem();
        item.Text = "";
        item.Value = "";
        ddlSection.Items.Add(item);
        
        ListItem item1 = new ListItem();
        item1.Text = "Pre-Filing";
        item1.Value = "1";
        ddlSection.Items.Add(item1);

        ListItem item2 = new ListItem();
        item2.Text = "Post-Filing";
        item2.Value = "2";
        ddlSection.Items.Add(item2);

        ListItem item3 = new ListItem();
        item3.Text = "Official Actions";
        item3.Value = "3";
        ddlSection.Items.Add(item3);

        ListItem item4 = new ListItem();
        item4.Text = "Finance";
        item4.Value = "4";
        ddlSection.Items.Add(item4);
         */

        IPTableAdapters.HeadingSectionTableAdapter ct = new IPTableAdapters.HeadingSectionTableAdapter();
        DataTable dt = ct.GetHeadingSectionData();
        ddlSection.DataSource = dt;
        ddlSection.DataTextField = "Description";
        ddlSection.DataValueField = "Section";
        ddlSection.DataBind();
        ddlSection.Items.Insert(0, new ListItem("", ""));
    }

    private void SetddlSection(string val)
    {
        for (int i = 0; i < ddlSection.Items.Count; i++)
        {
            if (ddlSection.Items[i].Value == val)
            {
                ddlSection.SelectedIndex = i;
                break;
            }
        }
    }

    private void ChangeDdlSection()
    {
        ddlSection.ClearSelection();
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        this.clearText();
        this.setButtons(string.Empty);
        this.setTextReadOnly(true);
        /******Modify by ljr*********/
        ClearGroupType();
        /***************/
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        Auth canDelete = new Auth(this.Session["UserId"].ToString(), string.Empty, "ProcedureTemplate");
        if (!canDelete.CanDelete())
        {
            this.lblError.Visible = true;
            this.lblError.Text = Messages.mNoDelete.ToString();
        }
        else
        {
            try
            {
                /******Modify by ljr*********/
                string strSection = ddlSection.SelectedItem.Value.ToString().Trim();
                string strType = txtHeadingCode.Text.Trim();
                /***************/
                this.ODSHeadingTmplt.DeleteMethod = "Delete";
                this.ODSHeadingTmplt.DeleteParameters["HeadingCode"].DefaultValue = strType;
                this.ODSHeadingTmplt.DeleteParameters["Section"].DefaultValue = strSection;
                this.ODSHeadingTmplt.Delete();

                /******Modify by ljr*********/
                string sqlStr = "delete from HeadingTemplateCode where Section='" + strSection + "' and HeadingCode='" + strType + "'";
                ClassLibrary.BusinessLayer.BusinessObjects.Db.Delete(sqlStr);
                /***************/

                this.setButtons(string.Empty);
                this.setTextReadOnly(true);
                this.clearText();
                this.Search();
            }
            catch (Exception ex)
            {
                List<string> lstValues = new List<string>();
                //this.lblError.Text = IPDataFormat.GenerateMessage(ex, lstValues);
                this.lblError.Text = ex.Message.ToString();
                this.chkForOperation.Checked = true;
            }
        }
        /******Modify by ljr*********/
        ClearGroupType();
        /***************/
    }

    protected void btnModify_Click(object sender, EventArgs e)
    {
        Auth canDelete = new Auth(this.Session["UserId"].ToString(), string.Empty, "ProcedureTemplate");
        if (!canDelete.CanUpdate())
        {
            this.lblError.Visible = true;
            this.lblError.Text = Messages.mNoEdit.ToString();
        }
        else
        {
            this.setButtons("modify");
            this.setTextReadOnly(false);
            this.txtHeadingCode.Enabled = false;
            this.ddlSection.Enabled = false;
            this.txtHeadingName.Focus();
            this.txtHeadingName.Attributes.Add("onfocusin", " select();");
        }
    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        Auth canDelete = new Auth(this.Session["UserId"].ToString(), string.Empty, "ProcedureTemplate");
        if (!canDelete.CanAdd())
        {
            this.lblError.Visible = true;
            this.lblError.Text = Messages.mNoAdd.ToString();
        }
        else
        {
            this.clearText();
            this.setButtons("new");
            this.setTextReadOnly(false);
            this.txtHeadingCode.Focus();
        }
        /******Modify by ljr*********/
        ClearGroupType();
        /***************/
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            string strSection = ddlSection.SelectedItem.Value.ToString();
            if ((((strSection != "1") & (strSection != "2")) & (strSection != "3")) & (strSection != "4"))
            {
                throw new Exception(Strings.SectionRange.ToString());
            }
            if (this.cbForUpdate.Checked)
            {
                this.ODSHeadingTmplt.UpdateMethod = "Update";
                this.ODSHeadingTmplt.UpdateParameters["HeadingName"].DefaultValue = this.txtHeadingName.Text.ToString();
                this.ODSHeadingTmplt.UpdateParameters["HeadingNameChinese"].DefaultValue = this.txtHeadingChineseName.Text.ToString();
                this.ODSHeadingTmplt.UpdateParameters["HeadingDescription"].DefaultValue = this.txtHeadingDescription.Text.ToString();
                this.ODSHeadingTmplt.UpdateParameters["UpdateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSHeadingTmplt.UpdateParameters["HeadingCode"].DefaultValue = this.txtHeadingCode.Text.ToString();
                this.ODSHeadingTmplt.UpdateParameters["Section"].DefaultValue = strSection.ToString();
                this.ODSHeadingTmplt.Update();
            }
            else
            {
                this.ODSHeadingTmplt.InsertMethod = "Insert";
                this.ODSHeadingTmplt.InsertParameters["HeadingCode"].DefaultValue = this.txtHeadingCode.Text.ToString();
                this.ODSHeadingTmplt.InsertParameters["HeadingName"].DefaultValue = this.txtHeadingName.Text.ToString();
                this.ODSHeadingTmplt.InsertParameters["HeadingNameChinese"].DefaultValue = this.txtHeadingChineseName.Text.ToString();
                this.ODSHeadingTmplt.InsertParameters["HeadingDescription"].DefaultValue = this.txtHeadingDescription.Text.ToString();
                this.ODSHeadingTmplt.InsertParameters["Section"].DefaultValue = strSection.ToString();
                this.ODSHeadingTmplt.InsertParameters["CreateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSHeadingTmplt.InsertParameters["UpdateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSHeadingTmplt.InsertParameters["OwnerGroupID"].DefaultValue = this.Session["OwnerGroupId"].ToString();
                this.ODSHeadingTmplt.Insert();
            }

            /******Modify by ljr*********/
            string strSql;
            string headingCode = txtHeadingCode.Text.Trim();
            strSql = "delete from HeadingTemplateCode where Section='" + strSection + "' and HeadingCode='" + headingCode + "'";
            ClassLibrary.BusinessLayer.BusinessObjects.Db.Delete(strSql);
            
            foreach (RepeaterItem rptItem in rptGroupType.Items)
            {
                CheckBox cb = (CheckBox)rptItem.FindControl("chkGroupTP");
                if (cb.Checked)
                {
                    string sqlInsert = "insert into HeadingTemplateCode (Section, HeadingCode, GroupTypeCode) values('" + strSection + "','" + headingCode + "','" + cb.Text.Trim() + "')";
                    ClassLibrary.BusinessLayer.BusinessObjects.Db.Insert(sqlInsert);
                }
            }
            ClearGroupType();
            /***************/

            this.setButtons(string.Empty);
            this.setTextReadOnly(true);
            this.clearText();
            this.Search();
        }
        catch (Exception ex)
        {
            List<string> lstValues = new List<string>();
            //this.lblError.Text = IPDataFormat.GenerateMessage(ex, lstValues);
            this.lblError.Text = ex.Message.ToString();
            this.chkForOperation.Checked = true;
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        this.Search();
    }

    protected void clearText()
    {
        this.txtHeadingCode.Text = string.Empty;
        this.txtHeadingName.Text = string.Empty;
        this.txtHeadingChineseName.Text = string.Empty;
        this.txtHeadingDescription.Text = string.Empty;
        this.ddlSection.SelectedIndex = 0;
        this.cbForUpdate.Checked = false;
        this.chkForOperation.Checked = false;
        this.lblError.Text = "";
    }

    protected void gvHeadingTmplt_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.gvHeadingTmplt.PageIndex = e.NewPageIndex;
        this.gvHeadingTmplt.DataBind();
        this.Search();
    }

    protected void gvHeadingTmplt_RowCreated(object sender, GridViewRowEventArgs e)
    {
        this.Sort(e, this.gvHeadingTmplt);
    }

    protected void gvHeadingTmplt_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.clearText();
        this.chkForOperation.Checked = true;
        this.cbForUpdate.Checked = true;

        /******Modify by ljr*********/
        ClearGroupType();

        string sqlStr = "select * from HeadingTemplateCode where Section='" + this.gvHeadingTmplt.DataKeys[this.gvHeadingTmplt.SelectedIndex].Values["Section"].ToString() + "' and HeadingCode='" + this.gvHeadingTmplt.DataKeys[this.gvHeadingTmplt.SelectedIndex].Values["HeadingCode"].ToString() + "'";
        DataTable dt = ClassLibrary.BusinessLayer.BusinessObjects.Db.GetDataTable(sqlStr);
        if (dt != null && dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                foreach (RepeaterItem rptItem in rptGroupType.Items)
                {
                    CheckBox cb = (CheckBox)rptItem.FindControl("chkGroupTP");
                    if (dt.Rows[i]["GroupTypeCode"].ToString() == cb.Text.Trim())
                    {
                        cb.Checked = true;
                        break;
                    }
                }
            }
        }
        /***************/

        string headingCode = this.gvHeadingTmplt.DataKeys[this.gvHeadingTmplt.SelectedIndex].Values["HeadingCode"].ToString();
        string section = this.gvHeadingTmplt.DataKeys[this.gvHeadingTmplt.SelectedIndex].Values["Section"].ToString();
        HeadingTmplts runMethod = new HeadingTmplts();
        //runMethod.GetHeadingTmpltInfo(headingCode, section);
        runMethod.GetHeadingTmpltInfo(headingCode,section);
        this.txtHeadingCode.Text = this.gvHeadingTmplt.DataKeys[this.gvHeadingTmplt.SelectedIndex].Values["HeadingCode"].ToString();
        SetddlSection(runMethod.Section);
        this.txtHeadingName.Text = runMethod.HeadingName;
        this.txtHeadingChineseName.Text = runMethod.HeadingNameChinese;
        this.txtHeadingDescription.Text = runMethod.HeadingDescription;
        this.setButtons(string.Empty);
    }

    protected override void InitializeCulture()
    {
        string sCulture = ConfigurationManager.AppSettings["DefaultCulture"].ToString();
        try
        {
            sCulture = this.Session["Culture"].ToString();
        }
        catch (NullReferenceException)
        {
        }
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(sCulture);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(sCulture);
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Auth canView = new Auth(this.Session["UserId"].ToString(), string.Empty, "ProcedureTemplate");
        if (!canView.CanView())
        {
            base.Response.Redirect("ErrorPage/NotAllowed.aspx");
        }
        else if (!this.Page.IsPostBack)
        {
            /******Modify by ljr*********/
            ((Label)this.Master.FindControl("lblMstTitle")).Text = " | " + ISitemap.Settings + " | " + ISitemap.ProcedureSetup + " | " + ISitemap.ProcedureTemplate;
            IPTableAdapters.CodeTableAdapter codeAd = new IPTableAdapters.CodeTableAdapter();
            IP.CodeDataTable dt = codeAd.GetCodesByType("PT");
            rptGroupType.DataSource = dt;
            rptGroupType.DataBind();
            ClearGroupType();
            InitddlSection();

            Search();
            /***************/

            this.setButtons(string.Empty);
            this.setTextReadOnly(true);
            this.btnDelete.Attributes.Add("onClick", "return confirm('" + Messages.DeleteConfirmation.ToString() + "')");
        }
    }

    protected void Search()
    {
        /*
        ProcedureTmpltFacade facade = new ProcedureTmpltFacade();
        SqlParameter[] sqlparam = new SqlParameter[2];
        sqlparam[0] = new SqlParameter();
        sqlparam[0].ParameterName = "@HeadingCode";
        sqlparam[0].Value = this.txtSearchProcCode.Text.ToString();
        sqlparam[1] = new SqlParameter();
        sqlparam[1].ParameterName = "@HeadingName";
        sqlparam[1].Value = this.txtSearchProcName.Text.ToString();
        DbParameter[] param = sqlparam;
        DataView dv = facade.GetsProcedureTmplt("_IPMS_HeadingTemplateSearch_SP", param).DefaultView;
        this.gvHeadingTmplt.DataSourceID = string.Empty;
        this.gvHeadingTmplt.DataSource = dv;
        this.gvHeadingTmplt.DataBind();*/
        IPTableAdapters.HeadingTemplateTableAdapter htta= new IPTableAdapters.HeadingTemplateTableAdapter();
        
        DataTable dt = htta.GetHeadingTemplateDataByljr(this.txtSearchProcCode.Text.ToString(), this.txtSearchProcName.Text.ToString());
        this.gvHeadingTmplt.DataSourceID = string.Empty;
        this.gvHeadingTmplt.DataSource = dt;
        this.gvHeadingTmplt.DataBind();
    }

    protected void setButtons(string action)
    {
        switch (action)
        {
            case "new":
                this.btnNew.Enabled = false;
                this.btnModify.Enabled = false;
                this.btnSave.Enabled = true;
                this.btnDelete.Enabled = false;
                return;

            case "modify":
                this.btnNew.Enabled = false;
                this.btnModify.Enabled = false;
                this.btnSave.Enabled = true;
                this.btnDelete.Enabled = false;
                return;
        }
        this.btnNew.Enabled = true;
        this.btnModify.Enabled = this.txtHeadingCode.Text.Length != 0;
        this.btnSave.Enabled = false;
        this.btnDelete.Enabled = this.txtHeadingCode.Text.Length != 0;
    }

    protected void setTextReadOnly(bool bBool)
    {
        this.txtHeadingCode.ReadOnly = bBool;
        this.txtHeadingName.ReadOnly = bBool;
        this.txtHeadingChineseName.ReadOnly = bBool;
        this.txtHeadingDescription.ReadOnly = bBool;
        this.txtHeadingCode.Enabled = !bBool;
        this.txtHeadingName.Enabled = !bBool;
        this.txtHeadingChineseName.Enabled = !bBool;
        this.txtHeadingDescription.Enabled = !bBool;
        this.ddlSection.Enabled = !bBool;
    }

    protected void Sort(GridViewRowEventArgs e, GridView gv)
    {
        if ((e.Row != null) && (e.Row.RowType == DataControlRowType.Header))
        {
            foreach (TableCell cell in e.Row.Cells)
            {
                if (cell.HasControls())
                {
                    LinkButton button = (LinkButton)cell.Controls[0];
                    if (button != null)
                    {
                        Image image = new Image();
                        image.ImageUrl = "";
                        if (gv.SortExpression == button.CommandArgument)
                        {
                            if (gv.SortDirection == SortDirection.Ascending)
                            {
                                image.ImageUrl = "images/sortup.gif";
                            }
                            else
                            {
                                image.ImageUrl = "images/sortdown.gif";
                            }
                        }
                        if (image.ImageUrl != "")
                        {
                            cell.Controls.Add(image);
                        }
                    }
                }
            }
        }
    }
}
